package cc.bandaoti.prototypeview;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;

@Controller
public class UploadController {
    private static final String BASE_DIR = "data";

    @GetMapping("/")
    public String index(Model model) {
        File baseDir = new File(BASE_DIR);
        Map<String, List<String>> projectVersions = new TreeMap<>();
        if (baseDir.exists()) {
            for (File project : Objects.requireNonNull(baseDir.listFiles(File::isDirectory))) {
                List<String> versions = new ArrayList<>();
                for (File version : Objects.requireNonNull(project.listFiles(File::isDirectory))) {
                    File indexFile = new File(version, "index.html");
                    if (indexFile.exists()) {
                        versions.add(version.getName());
                    }
                }
                if (!versions.isEmpty()) {
                    projectVersions.put(project.getName(), versions);
                }
            }
        }
        model.addAttribute("projects", projectVersions);
        return "index";
    }

    @PostMapping("/upload")
    public String handleUpload(@RequestParam("file") MultipartFile file, Model model) throws IOException {
        String filename = file.getOriginalFilename();
        if (filename == null || !filename.endsWith(".zip")) {
            model.addAttribute("message", "请上传 zip 格式文件");
            return "error";
        }

        String nameVer = filename.replace(".zip", "");
        int idx = nameVer.lastIndexOf("_");
        if (idx == -1) {
            model.addAttribute("message", "文件名格式错误，正确格式应为 项目名_版本.zip");
            return "error";
        }

        String project = nameVer.substring(0, idx);
        String version = nameVer.substring(idx + 1);
        File targetDir = new File(BASE_DIR + "/" + project + "/" + version);
        if (!targetDir.exists()) targetDir.mkdirs();

        File tempZip = File.createTempFile(nameVer, ".zip");
        file.transferTo(tempZip);

        // 复制压缩包到目标目录
        Files.copy(tempZip.toPath(), new File(BASE_DIR + "/" + project, filename).toPath());

        if (!ZipUtils.containsIndexHtml(tempZip)) {
            model.addAttribute("message", "压缩包中未包含 index.html 文件");
            return "error";
        }

        ZipUtils.unzip(tempZip.getAbsolutePath(), targetDir.getAbsolutePath());

        return "redirect:/";
    }

    @PostMapping("/delete")
    public String deleteVersion(@RequestParam("project") String project, @RequestParam("version") String version) throws IOException {
        File versionDir = new File(BASE_DIR + "/" + project + "/" + version);
        File zipFile = new File(BASE_DIR + "/" + project + "/" + project + "_" + version + ".zip");
        if (versionDir.exists()) ZipUtils.deleteRecursively(versionDir.toPath());
        if (zipFile.exists()) Files.delete(zipFile.toPath());
        // 如果BASE_DIR + "/" + project 内没有文件，将目录页删除
        if (Objects.requireNonNull(new File(BASE_DIR + "/" + project).listFiles()).length == 0) {
            Files.delete(new File(BASE_DIR + "/" + project).toPath());
        }
        return "redirect:/";
    }
}
